package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"mall-api-gin/pkg/app"
	"mall-api-gin/pkg/bizerror"
	"mall-api-gin/pkg/logging"
	"net/http"
)

type BaseController struct {
	app.Gin
}

//解析请求体中的json数据
func (base *BaseController) ParseJson(c *gin.Context, body interface{}) interface{} {
	err := c.Bind(body)
	if err != nil {
		logging.Error(err)
		base.ErrResponse(http.StatusBadRequest, bizcode.InvalidParams, err)
	}
	return &body
}

//异常处理
func (base *BaseController) PanicHandler(httpCode int) {
	if err := recover(); err != nil {
		fmt.Printf("源错误信息：%v\n", err)
		bizError := bizcode.BizCode500
		err, ok := err.(bizcode.BizCode)
		if ok {
			bizError = err
		}
		base.Response(bizError.HttpCode, bizError.Code, bizError.Msg)
		return
	}
}

// ErrResponse 构建异常响应
func (base *BaseController) ErrResponse(httpCode int, errCode int, msg interface{}) {
	bizcode.BizCodeHander.PanicError(httpCode, errCode, msg)
}

// SuccessResponse 构建成功响应
func (base *BaseController) SuccessResponse(httpCode int, errCode int, data interface{}) {
	response := app.NewResponse(httpCode, errCode, data)
	base.Response(httpCode, errCode, response)
	return
}

// Response 返回信息
func (base *BaseController) Response(httpCode int, errCode int, data interface{}) {
	base.C.JSON(httpCode, app.NewResponse(httpCode, errCode, data))
	return
}
